package com.haidechizi.longpolling.server.web;

import com.haidechizi.longpolling.event.LocalDataChangeEvent;
import com.haidechizi.longpolling.event.listener.EventDispatcher;
import com.haidechizi.longpolling.server.entity.ConfigData;
import com.haidechizi.longpolling.server.persistent.ConfigDataPersistent;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

/**
 * @author wangdejun
 * @create 2021/2/24 13:27
 */
@RestController
@RequestMapping("/configData")
public class ConfigDataController {

    @PostMapping("save")
    public String save(@Validated @RequestBody ConfigData configData) {
        ConfigDataPersistent.addConfigData(configData);
        // 触发数据更改事件
        EventDispatcher.fireEvent(new LocalDataChangeEvent(configData.getAppCode()));
        return "ok";
    }

    @GetMapping("get/{appCode}")
    public ConfigData get(@PathVariable String appCode) {
        return ConfigDataPersistent.getConfigData(appCode);
    }


    @PostMapping("list")
    public Collection<ConfigData> list() {
        return ConfigDataPersistent.configDataList();
    }
}
